'use strict';

const BaseController = require('./base');
const {sign} = require('jsonwebtoken');

class UserController extends BaseController {
   constructor(...args){
     super(...args);
     this.model = 'user';
   }
   //登陆
   async login(){
    let {ctx,app} = this;
    let body = ctx.request.body;//获得请求体 {username,password}
    const result = await app.mysql.select('user',{
      where:{
        username:body.username,
        password:body.password
      },
      offset:0,
      limit:1
    });
    //如果说查到了数据，则表示登陆是成功的
    if(result && result.length>0){
      let user = result[0];//jwt jsonwebtoken
      user = JSON.parse(JSON.stringify(user));//resources
      let resources = [];
      let list = await app.mysql.query(`SELECT resource.* FROM role_user 
      INNER JOIN role_resource ON role_user.role_id = role_resource.role_id
      INNER JOIN resource ON role_resource.resource_id =  resource.id
      WHERE role_user.user_id = ?`,user.id);
      let map = {};
      list.forEach(item=>{//只有2 parent_id = 1
        item.children = [];
        map[item.id] = item;
        if(item.parent_id===0){
          resources.push(item);
        }else{
          if(map[item.parent_id])
             map[item.parent_id].children.push(item);
        }
      });
      user.resources = resources;
      user.resourceList = list;
      this.success(sign(user,app.config.jwtSecret));
    }else{
      this.error('登录失败');
    }
   }
   //注册
   async signup(){
      let {ctx,app} = this;
      let body = ctx.request.body;//获得请求体 {username,password}
      let captcha = body.captcha;
      delete body.confirm;
      body.address  = body.address.join('-');
      delete body.aggrement;
      delete body.captcha;//因为验证码不需要保存数据库，所以取到之后可以直接 删除
      if(captcha && ctx.session.captcha && captcha==ctx.session.captcha){
        const result = await app.mysql.insert('user',body);
        if(result.affectedRows >0){
          this.success('注册成功');
        }else{
          this.error('注册失败');
        }
      }else{
        this.error('注册失败');
      }
   }
}

module.exports = UserController;
